<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>检查记录查询 - 实验室辅助管理系统</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <link rel="stylesheet" th:href="@{/css/fontawesome-local.css}">
    <style>
        .search-section {
            background: linear-gradient(135deg, #1a73e8, #0d47a1);
            color: white;
            padding: 25px;
            border-radius: 10px;
            margin-bottom: 25px;
        }

        .search-section h3 {
            margin: 0 0 20px 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .search-form {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            align-items: end;
        }

        .search-form .form-group {
            margin: 0;
        }

        .search-form label {
            color: #000000;
            font-weight: 500;
            margin-bottom: 8px;
            display: block;
        }

        .search-form .form-control {
            background: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: #000000;
            border-radius: 6px;
        }

        .search-form .form-control::placeholder {
            color: rgba(0, 0, 0, 0.5);
        }

        .search-form .form-control:focus {
            background: rgba(255, 255, 255, 1);
            border-color: rgba(26, 115, 232, 0.5);
            box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.1);
            color: #000000;
        }

        .btn-search {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .btn-search:hover {
            background: rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
        }

        .btn-clear {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .btn-clear:hover {
            background: rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
        }

        .records-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }

        .stat-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-left: 4px solid #1a73e8;
        }

        .stat-card.normal {
            border-left-color: #34a853;
        }

        .stat-card.abnormal {
            border-left-color: #ea4335;
        }

        .stat-card.total {
            border-left-color: #1a73e8;
        }

        .stat-number {
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .stat-card.normal .stat-number {
            color: #34a853;
        }

        .stat-card.abnormal .stat-number {
            color: #ea4335;
        }

        .stat-card.total .stat-number {
            color: #1a73e8;
        }

        .stat-label {
            color: #666;
            font-weight: 500;
        }

        .records-table {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .table-header {
            background: #f8f9fa;
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .table-header h3 {
            margin: 0;
            color: #1a73e8;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .table-responsive {
            overflow-x: auto;
        }

        .table {
            width: 100%;
            margin: 0;
            border-collapse: collapse;
        }

        .table th {
            background: #1a73e8;
            color: white;
            padding: 15px 12px;
            text-align: left;
            font-weight: 600;
            border: none;
        }

        .table td {
            padding: 15px 12px;
            border-bottom: 1px solid #e9ecef;
            vertical-align: middle;
        }

        .table tbody tr:hover {
            background-color: #f8f9fa;
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-normal {
            background: #e8f5e8;
            color: #2e7d32;
        }

        .status-abnormal {
            background: #ffebee;
            color: #c62828;
        }

        .status-handled {
            background: #e8f5e8;
            color: #2e7d32;
        }

        .status-pending {
            background: #fff3e0;
            color: #f57c00;
        }

        .detail-items {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .detail-item {
            background: #f0f0f0;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
        }

        .detail-item.problem {
            background: #ffebee;
            color: #c62828;
        }

        .detail-item.normal {
            background: #e8f5e8;
            color: #2e7d32;
        }

        .btn-view {
            background: #1a73e8;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }

        .btn-view:hover {
            background: #0d47a1;
        }

        .btn-handle {
            background: #4caf50;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 11px;
            transition: all 0.3s ease;
        }

        .btn-handle:hover {
            background: #45a049;
        }

        .btn-export {
            background: #ff9800;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 11px;
            transition: all 0.3s ease;
        }

        .btn-export:hover {
            background: #f57c00;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            color: #ddd;
        }

        .empty-state h3 {
            margin: 0 0 10px 0;
            color: #999;
        }

        .empty-state p {
            margin: 0;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            padding: 20px;
            background: #f8f9fa;
        }

        .pagination button {
            background: white;
            border: 1px solid #ddd;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .pagination button:hover:not(:disabled) {
            background: #1a73e8;
            color: white;
            border-color: #1a73e8;
        }

        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .pagination .current-page {
            background: #1a73e8;
            color: white;
            border-color: #1a73e8;
        }

        @media (max-width: 768px) {
            .search-form {
                grid-template-columns: 1fr;
            }
            
            .records-stats {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .table-responsive {
                font-size: 12px;
            }
            
            .table th,
            .table td {
                padding: 8px 6px;
            }
            
            /* 在小屏幕上隐藏一些不重要的列 */
            .table th:nth-child(3),
            .table td:nth-child(3),
            .table th:nth-child(7),
            .table td:nth-child(7) {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="management-container">
        <!-- 侧边栏 -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <h2><i class="fas fa-search"></i> 记录查询</h2>
            </div>
            <ul class="nav-menu">
                <li th:if="${currentUser.role.name() == 'ADMIN'}"><a th:href="@{/dashboard}"><i class="fas fa-tachometer-alt"></i> 系统仪表盘</a></li>
                <li><a th:href="@{/safety-check}"><i class="fas fa-clipboard-check"></i> 安全检查登记</a></li>
                <li class="active"><a th:href="@{/safety-records}"><i class="fas fa-search"></i> 检查记录查询</a></li>
                <li th:if="${currentUser.role.name() == 'ADMIN'}"><a th:href="@{/college-management}"><i class="fas fa-university"></i> 学院管理</a></li>
                <li th:if="${currentUser.role.name() == 'ADMIN'}"><a th:href="@{/term-management}"><i class="fas fa-calendar-alt"></i> 学期管理</a></li>
                <li th:if="${currentUser.role.name() == 'ADMIN'}"><a th:href="@{/laboratory-management}"><i class="fas fa-microscope"></i> 实验室管理</a></li>
                <li th:if="${currentUser.role.name() == 'ADMIN'}"><a th:href="@{/user-management}"><i class="fas fa-users"></i> 用户管理</a></li>
                <li th:if="${currentUser.role.name() == 'ADMIN'}"><a th:href="@{/assignment-management}"><i class="fas fa-user-cog"></i> 管理员分配</a></li>
            </ul>
        </nav>

        <!-- 主内容区 -->
        <main class="main-content">
            <!-- 顶部栏 -->
            <header class="top-bar">
                <div class="top-bar-left">
                    <h1>安全检查记录查询</h1>
                </div>
                <div class="top-bar-right">
                    <div class="user-info">
                        <span th:text="${currentUser.name}">管理员</span>
                        <a th:href="@{/logout}" class="logout-btn">退出</a>
                    </div>
                </div>
            </header>

            <!-- 内容区域 -->
            <div class="content">
                <!-- 搜索区域 -->
                <div class="search-section">
                    <h3><i class="fas fa-filter"></i> 搜索条件</h3>
                    <form class="search-form" id="searchForm">
                        <div class="form-group">
                            <label for="searchTerm">学期</label>
                            <select id="searchTerm" class="form-control">
                                <option value="">全部学期</option>
                                <option th:each="term : ${terms}" 
                                        th:value="${term.id}" 
                                        th:text="${term.name}"
                                        th:selected="${term.status == T(com.it.labservice.entity.Term$TermStatus).CURRENT}">2023学年下学期</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="searchLab">实验室</label>
                            <select id="searchLab" class="form-control">
                                <option value="">全部实验室</option>
                                <option th:each="lab : ${userLaboratories}" 
                                        th:value="${lab.id}" 
                                        th:text="${lab.name}">计算机基础实验室</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="searchStatus">检查结果</label>
                            <select id="searchStatus" class="form-control">
                                <option value="">全部结果</option>
                                <option value="normal">正常</option>
                                <option value="abnormal">异常</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="startDate">开始日期</label>
                            <input type="date" id="startDate" class="form-control">
                        </div>

                        <div class="form-group">
                            <label for="endDate">结束日期</label>
                            <input type="date" id="endDate" class="form-control">
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn-search">
                                <i class="fas fa-search"></i>
                                搜索
                            </button>
                        </div>
                        
                        <div class="form-group">
                            <button type="button" onclick="clearFilters()" class="btn-clear">
                                <i class="fas fa-times"></i>
                                清空
                            </button>
                        </div>
                    </form>
                </div>

                <!-- 统计数据 -->
                <div class="records-stats">
                    <div class="stat-card total">
                        <div class="stat-number" id="totalCount">0</div>
                        <div class="stat-label">总检查次数</div>
                    </div>
                    <div class="stat-card normal">
                        <div class="stat-number" id="normalCount">0</div>
                        <div class="stat-label">正常检查</div>
                    </div>
                    <div class="stat-card abnormal">
                        <div class="stat-number" id="abnormalCount">0</div>
                        <div class="stat-label">异常检查</div>
                    </div>
                    <div class="stat-card" style="border-left-color: #ff9800;">
                        <div class="stat-number" id="pendingCount" style="color: #ff9800;">0</div>
                        <div class="stat-label">待处理</div>
                    </div>
                </div>

                <!-- 检查记录表格 -->
                <div class="records-table">
                    <div class="table-header">
                        <h3><i class="fas fa-list"></i> 检查记录列表</h3>
                        <button onclick="exportAllRecords()" style="background: #4caf50; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">
                            <i class="fas fa-file-excel"></i> 导出Excel
                        </button>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table" id="recordsTable">
                            <thead>
                                <tr>
                                    <th>检查日期</th>
                                    <th>学期</th>
                                    <th>实验室</th>
                                    <th>检查人员</th>
                                    <th>检查结果</th>
                                    <th>处理状态</th>
                                    <th>处理时间</th>
                                    <th>问题项目</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="recordsTableBody">
                                <!-- 动态加载数据 -->
                            </tbody>
                        </table>
                    </div>

                    <!-- 空状态 -->
                    <div class="empty-state" id="emptyState" style="display: none;">
                        <i class="fas fa-search"></i>
                        <h3>暂无记录</h3>
                        <p>没有找到符合条件的检查记录</p>
                    </div>

                    <!-- 分页 -->
                    <div class="pagination" id="pagination" style="display: none;">
                        <button id="prevPage"><i class="fas fa-chevron-left"></i></button>
                        <span id="pageInfo">第 1 页，共 1 页</span>
                        <button id="nextPage"><i class="fas fa-chevron-right"></i></button>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script th:src="@{/js/app.js}"></script>
    <script>
        // 真实数据存储
        let allRecords = [];
        let currentRecords = [];
        let currentPage = 1;
        const recordsPerPage = 10;

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadAllRecords();
        });
        
        // 从服务器加载所有记录
        function loadAllRecords() {
            fetch('/api/safety-records')
                .then(response => response.json())
                .then(data => {
                    if (Array.isArray(data)) {
                        allRecords = data;
                        currentRecords = [...allRecords];
                        loadRecords();
                        updateStats();
                    } else {
                        console.error('获取记录失败:', data.message);
                        allRecords = [];
                        currentRecords = [];
                        loadRecords();
                        updateStats();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    allRecords = [];
                    currentRecords = [];
                    loadRecords();
                    updateStats();
                });
        }

        // 搜索表单提交
        document.getElementById('searchForm').addEventListener('submit', function(e) {
            e.preventDefault();
            searchRecords();
        });

        function searchRecords() {
            // 获取搜索条件
            const term = document.getElementById('searchTerm').value;
            const lab = document.getElementById('searchLab').value;
            const status = document.getElementById('searchStatus').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;

            // 构建查询参数
            const params = new URLSearchParams();
            if (term) params.append('termId', term);
            if (lab) params.append('laboratoryId', lab);
            if (status) params.append('status', status);
            if (startDate) params.append('startDate', startDate);
            if (endDate) params.append('endDate', endDate);

            // 从服务器获取过滤后的记录
            fetch('/api/safety-records?' + params.toString())
                .then(response => response.json())
                .then(data => {
                    if (Array.isArray(data)) {
                        currentRecords = data;
                    } else {
                        console.error('搜索失败:', data.message);
                        currentRecords = [];
                    }
                    currentPage = 1;
                    loadRecords();
                    updateStats();
                })
                .catch(error => {
                    console.error('Error:', error);
                    currentRecords = [];
                    loadRecords();
                    updateStats();
                });
        }

        function loadRecords() {
            const tbody = document.getElementById('recordsTableBody');
            const emptyState = document.getElementById('emptyState');
            const pagination = document.getElementById('pagination');

            if (currentRecords.length === 0) {
                tbody.innerHTML = '';
                emptyState.style.display = 'block';
                pagination.style.display = 'none';
                return;
            }

            emptyState.style.display = 'none';
            
            // 分页计算
            const startIndex = (currentPage - 1) * recordsPerPage;
            const endIndex = startIndex + recordsPerPage;
            const pageRecords = currentRecords.slice(startIndex, endIndex);

            // 生成表格行
            tbody.innerHTML = pageRecords.map(record => {
                const problemItems = getProblems(record.details);
                // 如果是正常状态，直接显示已处理；如果是异常状态，根据handleStatus显示
                const handleStatusText = record.status === 'normal' ? '已处理' : 
                                       (record.handleStatus === 'HANDLED' ? '已处理' : '待处理');
                const handleStatusClass = (record.status === 'normal' || record.handleStatus === 'HANDLED') ? 'handled' : 'pending';
                
                return `
                    <tr>
                        <td>${record.date}</td>
                        <td>${record.term}</td>
                        <td>${record.laboratory}</td>
                        <td>${record.checker}</td>
                        <td>
                            <span class="status-badge status-${record.status}">
                                ${record.status === 'normal' ? '正常' : '异常'}
                            </span>
                        </td>
                        <td>
                            <span class="status-badge status-${handleStatusClass}">
                                ${handleStatusText}
                            </span>
                            ${record.status === 'abnormal' && record.handleStatus === 'PENDING' ? 
                                `<br><button class="btn-handle" onclick="markAsHandled(${record.id})" style="margin-top: 5px;">
                                    <i class="fas fa-check"></i> 标记已处理
                                </button>` : ''
                            }
                        </td>
                        <td>
                            ${record.handleTime ? formatDateTime(record.handleTime) : 
                              (record.status === 'normal' ? formatDateTime(record.date + 'T00:00:00') : '-')
                            }
                        </td>
                        <td>
                            <div class="detail-items">
                                ${problemItems.length > 0 ? 
                                    problemItems.map(item => `<span class="detail-item problem">${item}</span>`).join('') :
                                    '<span class="detail-item normal">无异常</span>'
                                }
                            </div>
                        </td>
                        <td>
                            <button class="btn-view" onclick="viewRecord(${record.id})">
                                <i class="fas fa-eye"></i> 查看详情
                            </button>
                            <br>
                            <button class="btn-export" onclick="exportRecord(${record.id})" style="margin-top: 5px;">
                                <i class="fas fa-download"></i> 导出
                            </button>
                        </td>
                    </tr>
                `;
            }).join('');

            // 更新分页
            updatePagination();
        }

        function getProblems(details) {
            const problems = [];
            const itemNames = {
                window: '门窗',
                circuit: '电路',
                fire: '消防',
                equipment: '设备',
                items: '物品',
                hygiene: '卫生'
            };

            Object.keys(details).forEach(key => {
                if (details[key] === 'problem') {
                    problems.push(itemNames[key]);
                }
            });

            return problems;
        }

        function updateStats() {
            const total = currentRecords.length;
            const normal = currentRecords.filter(r => r.status === 'normal').length;
            const abnormal = currentRecords.filter(r => r.status === 'abnormal').length;
            const pending = currentRecords.filter(r => r.handleStatus === 'PENDING' && r.status === 'abnormal').length;

            document.getElementById('totalCount').textContent = total;
            document.getElementById('normalCount').textContent = normal;
            document.getElementById('abnormalCount').textContent = abnormal;
            document.getElementById('pendingCount').textContent = pending;
        }

        function updatePagination() {
            const totalPages = Math.ceil(currentRecords.length / recordsPerPage);
            const pagination = document.getElementById('pagination');
            const pageInfo = document.getElementById('pageInfo');
            const prevBtn = document.getElementById('prevPage');
            const nextBtn = document.getElementById('nextPage');

            if (totalPages <= 1) {
                pagination.style.display = 'none';
                return;
            }

            pagination.style.display = 'flex';
            pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
            
            prevBtn.disabled = currentPage === 1;
            nextBtn.disabled = currentPage === totalPages;

            prevBtn.onclick = () => {
                if (currentPage > 1) {
                    currentPage--;
                    loadRecords();
                }
            };

            nextBtn.onclick = () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    loadRecords();
                }
            };
        }

        function viewRecord(recordId) {
            const record = currentRecords.find(r => r.id === recordId);
            if (!record) return;

            const details = record.details;
            const itemNames = {
                window: '门窗安全',
                circuit: '电路安全',
                fire: '消防设施',
                equipment: '仪器设备',
                items: '物品摆放',
                hygiene: '清洁卫生'
            };

            let detailsHtml = '';
            Object.keys(details).forEach(key => {
                const status = details[key] === 'ok' ? '正常' : '异常';
                const statusClass = details[key] === 'ok' ? 'normal' : 'problem';
                detailsHtml += `<p><strong>${itemNames[key]}:</strong> <span class="status-${statusClass}">${status}</span></p>`;
            });

            const modalHtml = `
                <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; display: flex; align-items: center; justify-content: center;" onclick="this.remove()">
                    <div style="background: white; padding: 30px; border-radius: 10px; max-width: 600px; width: 90%; max-height: 80vh; overflow-y: auto;" onclick="event.stopPropagation()">
                        <h3 style="margin: 0 0 20px; color: #1a73e8; display: flex; align-items: center; gap: 10px;">
                            <i class="fas fa-clipboard-list"></i> 检查记录详情
                        </h3>
                        
                        <div style="margin-bottom: 20px;">
                            <p><strong>检查日期:</strong> ${record.date}</p>
                            <p><strong>学期:</strong> ${record.term}</p>
                            <p><strong>实验室:</strong> ${record.laboratory}</p>
                            <p><strong>检查人员:</strong> ${record.checker}</p>
                            <p><strong>总体结果:</strong> 
                                <span class="status-badge status-${record.status}">
                                    ${record.status === 'normal' ? '正常' : '异常'}
                                </span>
                            </p>
                            <p><strong>处理状态:</strong> 
                                <span class="status-badge status-${(record.status === 'normal' || record.handleStatus === 'HANDLED') ? 'handled' : 'pending'}">
                                    ${record.status === 'normal' ? '已处理' : (record.handleStatus === 'HANDLED' ? '已处理' : '待处理')}
                                </span>
                            </p>
                            <p><strong>处理时间:</strong> ${record.handleTime ? formatDateTime(record.handleTime) : 
                              (record.status === 'normal' ? formatDateTime(record.date + 'T00:00:00') : '暂未处理')}</p>
                        </div>

                        <h4 style="color: #1a73e8; margin: 20px 0 10px;">检查详情</h4>
                        <div style="background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 20px;">
                            ${detailsHtml}
                        </div>

                        ${record.otherIssues ? `
                            <h4 style="color: #ea4335; margin: 20px 0 10px;">其他问题</h4>
                            <div style="background: #ffebee; padding: 15px; border-radius: 6px; margin-bottom: 20px;">
                                <p>${record.otherIssues}</p>
                            </div>
                        ` : ''}

                        <div style="text-align: center;">
                            <button onclick="closeModal()" style="background: #1a73e8; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer;">
                                关闭
                            </button>
                        </div>
                    </div>
                </div>
            `;

            document.body.insertAdjacentHTML('beforeend', modalHtml);
        }

        function closeModal() {
            const modal = document.querySelector('[style*="position: fixed"]');
            if (modal) {
                modal.remove();
            }
        }

        // 格式化日期时间
        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return '-';
            
            try {
                const date = new Date(dateTimeStr);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                
                // 如果时间是00:00，只显示日期
                if (hours === '00' && minutes === '00') {
                    return `${year}-${month}-${day}`;
                } else {
                    return `${year}-${month}-${day} ${hours}:${minutes}`;
                }
            } catch (error) {
                return '-';
            }
        }

        // 标记为已处理
        function markAsHandled(recordId) {
            if (confirm('确定要标记这条记录为已处理吗？')) {
                fetch(`/api/safety-records/${recordId}/handle`, {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage(data.message, 'success');
                        // 重新加载记录
                        loadAllRecords();
                    } else {
                        showMessage('标记失败：' + data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('标记失败，请稍后重试', 'error');
                });
            }
        }

        // 导出单条记录
        function exportRecord(recordId) {
            showMessage('正在导出Excel文件，请稍候...', 'info');
            
            fetch(`/api/safety-records/${recordId}/export`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('导出失败');
                    }
                    return response.blob();
                })
                .then(blob => {
                    // 创建下载链接
                    const url = window.URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = `安全检查记录_${recordId}.xlsx`;
                    link.style.display = 'none';
                    
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    
                    // 释放URL对象
                    window.URL.revokeObjectURL(url);
                    
                    showMessage('Excel文件导出完成！', 'success');
                })
                .catch(error => {
                    console.error('导出错误:', error);
                    showMessage('导出失败，请稍后重试', 'error');
                });
        }

        // 批量导出功能
        function exportAllRecords() {
            showMessage('正在导出Excel文件，请稍候...', 'info');
            
            const params = new URLSearchParams();
            const term = document.getElementById('searchTerm').value;
            const lab = document.getElementById('searchLab').value;
            const status = document.getElementById('searchStatus').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;

            if (term) params.append('termId', term);
            if (lab) params.append('laboratoryId', lab);
            if (status) params.append('status', status);
            if (startDate) params.append('startDate', startDate);
            if (endDate) params.append('endDate', endDate);

            fetch('/api/safety-records/export?' + params.toString())
                .then(response => {
                    if (!response.ok) {
                        throw new Error('导出失败');
                    }
                    return response.blob();
                })
                .then(blob => {
                    // 创建下载链接
                    const url = window.URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = `安全检查记录_${new Date().toISOString().slice(0, 10)}.xlsx`;
                    link.style.display = 'none';
                    
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    
                    // 释放URL对象
                    window.URL.revokeObjectURL(url);
                    
                    showMessage('Excel文件导出完成！', 'success');
                })
                .catch(error => {
                    console.error('导出错误:', error);
                    showMessage('导出失败，请稍后重试', 'error');
                });
        }

        // 清空筛选条件
        function clearFilters() {
            document.getElementById('searchTerm').value = '';
            document.getElementById('searchLab').value = '';
            document.getElementById('searchStatus').value = '';
            document.getElementById('startDate').value = '';
            document.getElementById('endDate').value = '';
            
            // 重新加载所有记录
            currentRecords = [...allRecords];
            currentPage = 1;
            loadRecords();
            updateStats();
        }

        // Element UI 风格消息提示
        function showMessage(message, type = 'info') {
            const colors = {
                success: '#67C23A',
                error: '#F56C6C',
                warning: '#E6A23C',
                info: '#409EFF'
            };
            
            const messageEl = document.createElement('div');
            messageEl.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: white;
                color: ${colors[type]};
                padding: 15px 20px;
                border: 1px solid ${colors[type]};
                border-radius: 4px;
                box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
                z-index: 9999;
                font-size: 14px;
                max-width: 300px;
                transform: translateX(100%);
                transition: transform 0.3s ease;
            `;
            messageEl.innerHTML = `
                <div style="display: flex; align-items: center; gap: 8px;">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'times-circle' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'}"></i>
                    <span>${message}</span>
                    <i class="fas fa-times" style="margin-left: auto; cursor: pointer; opacity: 0.6;" onclick="this.closest('div').parentElement.remove()"></i>
                </div>
            `;
            
            document.body.appendChild(messageEl);
            
            // 滑入动画
            setTimeout(() => {
                messageEl.style.transform = 'translateX(0)';
            }, 10);
            
            // 4秒后自动消失
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.style.transform = 'translateX(100%)';
                    setTimeout(() => {
                        if (messageEl.parentNode) {
                            messageEl.remove();
                        }
                    }, 300);
                }
            }, 4000);
        }
    </script>
</body>
</html> 